<template>
  <a-table :data-source="listData"
           :pagination="pagination"
           :rowKey="(record, index) => index"
           ref="table"
           @change="handleTableChange"
           :columns="columns"
           :row-class-name="(record, index) => (record.isLimit=='1'&&searchReq.type=='1'?'ft-red':'')">
    <span slot="resource"
          slot-scope="text, record">
      <a @click="toHref(record)" :title="record.title"
         :class="[record.readStatus=='2'&&searchReq.type=='3'?'ft-bold': '',record.isLimit=='1'&&searchReq.type=='1'?'ft-red':'']">
        {{ text }}
      </a>
    </span>
    <div slot="appName"
         class="appName"
         slot-scope="text">
      {{ text }}
    </div>
    <span slot="action"
          slot-scope="text, record">
      <template>
        <a @click="toHref(record)">详情</a>
      </template>
    </span>
  </a-table>
</template>
<script>
import dayjs from 'dayjs'
import storage from '@zh/common-utils/utils/storage'
import {
  PAGINATION,
  FONT_COLOR,
  DATETIME_FORMAT
} from '@zh/base-ant/framework/constants'
import { pageByType, updateTaskStatus } from '@zh/base-ant/framework/api/task'
export default {
  props: {
    searchReq: {
      type: Object | String | Number | Array,
      description: '搜索条件'
    }
  },
  data () {
    return {
      listData: [],
      fontColor: FONT_COLOR,
      pagination: PAGINATION,
      columns: [
        {
          title: '标题',
          dataIndex: 'title',
          ellipsis: true,
          scopedSlots: { customRender: 'resource' }
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unitName',
          scopedSlots: { customRender: 'unitName' },
          ellipsis: true
        },
        {
          title: '发起人',
          align: 'center',
          width: 150,
          dataIndex: 'ownerName'
        },
        {
          title: '发起时间',
          align: 'center',
          width: 200,
          dataIndex: 'createTime',
          customRender: (v) => (v ? v.substring(0, 16) : '')
        },
        {
          title: '来源',
          align: 'center',
          width: 150,
          dataIndex: 'appName',
          scopedSlots: { customRender: 'appName' }
        },
        {
          title: '操作',
          width: 130,
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ]
    }
  },
  watch: {
    'searchReq.type': {
      handler: function (val, oldVal) {
        if (val == '3') {
          let sta = this.columns.filter((e) => {
            return e.dataIndex == 'readStatus'
          })
          if (sta.length <= 0) {
            this.columns.splice(4, 0, {
              title: '状态',
              width: 80,
              align: 'center',
              dataIndex: 'readStatus',
              customRender: (v) => (v == '2' ? '未读' : '已读')
            })
          }

          this.columns = this.columns.filter((e) => {
            return e.dataIndex !== 'flowState'
          })
        } else if (val == '2' || val == '4') {
          this.columns = this.columns.filter((e) => {
            return e.dataIndex !== 'readStatus' && e.dataIndex !== 'flowState'
          })
          let sta = this.columns.filter((e) => {
            return e.dataIndex == 'flowState'
          })
          if (sta.length <= 0) {
            this.columns.splice(4, 0, {
              title: '流程状态',
              width: 120,
              align: 'center',
              dataIndex: 'flowState',
              customRender: (v) =>
                v == '0' ? '审核中' : v == '2' ? '已驳回' : '已通过'
            })
          }
          this.columns = this.columns.filter((e) => {
            return e.dataIndex !== 'readStatus'
          })
        } else {
          this.columns = this.columns.filter((e) => {
            return e.dataIndex !== 'readStatus' && e.dataIndex !== 'flowState'
          })
        }
      }
    }
  },
  // created () {
  //   this.load(this.searchReq)
  // },
  activated () {
    this.load(this.searchReq)
  },
  methods: {
    // 跳转详情
    toHref (item) {
      let itemType = this.searchReq.type == '1' ? '2' : '1'
      let bool = RegExp(/&itemType=/).test(item.url)
      if (!bool) {
        item.url = item.url + '&itemType=' + itemType
      }

      if (item.readStatus == '2' && this.searchReq.type == '3') {
        updateTaskStatus(item.taskId).then((res) => { })
      }

      const token = storage.getToken()?.value || ''
      const url = item.url.substring(0, item.url.lastIndexOf('?'))
      if (url == '/formPreview') {
        this.$router.push(item.url)
        return
      }
      if (item.category == '1') {
        this.$router.push(item.url)
      } else {
        if (!item.ssoLoginUrl) {
          let text = this.$router.resolve({
            path: item.url
          })
          // 打开一个新的页面
          window.open(text.href, '_blank')
          return
        }
        window.open(
          `${item.ssoLoginUrl}?targetUrl=${encodeURIComponent(
            item.url
          )}&token=${token}`
        )
      }

      if (item.category == '1') {
        // 本应用打开
        this.$router.push(item.url)
      } else {
        window.open(
          `${item.ssoLoginUrl}?targetUrl=${encodeURIComponent(
            item.url
          )}&token=${storage.getToken()?.value || ''}`
        )
      }
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.currPage = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.load({ ...this.searchReq, ...this.pagination })
    },
    // 列表数据
    load (searchReq, callback, tabKey) {
      // searchReq.type = tabKey
      pageByType(searchReq).then((res) => {
        this.listData = []
        const result = res.list
        this.pagination.current = res.currPage
        this.pagination.pageSize = res.pageSize
        this.pagination.total = res.totalCount
        for (const resultValue of result) {
          const createTime = resultValue?.createTime || ''
          const limitTime = resultValue?.limitTime || ''
          let description = '发送时间：' + createTime
          if (resultValue.limitTime != null) {
            description += '&emsp;&emsp;   办结时限：' + limitTime
          }
          if (resultValue.isLimitTime == '1') {
            description =
              '发送时间：' + dayjs(createTime).format(DATETIME_FORMAT.DATETIME)
            if (resultValue.limitTime != null) {
              description +=
                '&emsp;&emsp;   <label style="color:red;">办结时限：' +
                dayjs(limitTime).format(DATETIME_FORMAT.DATETIME)
            }
            description += '</label>'
          }
          // let i = resultValue.subject != '' ? resultValue.subject.lastIndexOf('】') : '',
          //   newTitle = resultValue.subject.substring(i + 1, resultValue.subject.length)

          this.listData.push({
            href: resultValue.url,
            // title: newTitle,
            title: resultValue.subject,
            ownerName: resultValue.ownerName,
            unitName: resultValue.unitName,
            url: resultValue.url,
            appName: resultValue.appName,
            description: description,
            createTime: resultValue.createTime,
            // createTime: resultValue.createTime ? resultValue.createTime.substring(0, 16) : '',
            isHasten: resultValue.isHasten,
            ponderanceId: resultValue.ponderanceId,
            appLogo: resultValue.appLogo,
            category: resultValue.category,
            readStatus: resultValue.readStatus,
            taskId: resultValue.taskId,
            ssoLoginUrl: resultValue.ssoLoginUrl || '',
            mobileLoginUrl: resultValue.mobileLoginUrl || '',
            isLimit: resultValue.isLimit,
            flowState: resultValue.flowState,
            tcHastenMsg:
              '[' +
              dayjs(resultValue.hastenTime).format(
                DATETIME_FORMAT.MONTH_DAY_TIME
              ) +
              ']&emsp;' +
              resultValue.hasteneOr +
              '：' +
              resultValue.tcHastenMsg
          })
        }
        if (callback) {
          callback(tabKey)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.appName {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
:deep(.ant-empty-description) {
  font-size: var(--font-size-18);
  color: #9f9f9f;
}
:deep(.ant-empty-image) {
  height: 80px;
}
.ft-bold {
  font-weight: bold;
}
.ft-red {
  color: #f5222d;
}
:deep(.ant-table-tbody) > tr.ft-red > td {
  color: #f5222d;
}
</style>
